public class LongestCommonSubsequence {

    public int longestCommonSubsequence(String text1, String text2) {
        int n = text1.length();
        int m = text2.length();
        char[] char1 = text1.toCharArray();
        char[] char2 = text2.toCharArray();
        int[][] dp = new int[n][m];
        dp[0][0] = char1[0] == char2[0] ? 1 : 0;
        for (int i = 1; i < m; i++) {
            dp[0][i] = Math.max(dp[0][i - 1], char1[0] == char2[i] ? 1 : 0);
        }
        for (int i = 1; i < n; i++) {
            dp[i][0] = Math.max(dp[i - 1][0], char1[i] == char2[0] ? 1 : 0);
        }
        for (int i = 1; i < n; i++) {
            for (int j = 1; j < m; j++) {
                dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                if (char1[i] == char2[j]) {
                    dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - 1] + 1);
                }
            }
        }
        return dp[n - 1][m - 1];
    }
}
